package com.mop.sg2.map;

import org.apache.mina.core.buffer.IoBuffer;

public class MessageExample {

	String name = null;

	int year = 0;

	short sex = 0;

	double m = 0;

	byte vip = 0;

	public void init(IoBuffer buffer) {
		// 读取String
		buffer.flip();
		int id = buffer.getShort();
		System.out.println("Message Id:" + id);

		int length = buffer.getShort();
		IoBuffer tmp = IoBuffer.allocate(length);
		tmp.put(buffer.getSlice(length));
		name = new String(tmp.array());

		// 读取int
		year = buffer.getInt();

		// 读取short
		sex = buffer.getShort();

		// 读取double
		m = buffer.getDouble();

		vip = buffer.get();
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getYear() {
		return year;
	}

	public void setYear(int year) {
		this.year = year;
	}

	public short getSex() {
		return sex;
	}

	public void setSex(short sex) {
		this.sex = sex;
	}

	public double getM() {
		return m;
	}

	public void setM(double m) {
		this.m = m;
	}

	public IoBuffer write() {
		IoBuffer buffer = IoBuffer.allocate(1024);
		//
		buffer.position(2);

		buffer.putShort((short) 1);

		// 写一个String
		byte[] string_byte = name.getBytes();

		buffer.putShort((short) string_byte.length);

		buffer.put(string_byte);

		// 写一个Int
		buffer.putInt(year);

		// 写一个Short
		buffer.putShort(sex);

		// 写一个double
		buffer.putDouble(m);

		//写一个byte
		buffer.put(vip);
		//
		int length = buffer.position();

		buffer.position(0);
		buffer.putShort((short)(length - 2));

		buffer.position(length);
		buffer.flip();

		return buffer;
	}

}
